<template>
	<view class="">

		<view class="cashierDeductionPage">
			<view class="viewDetailsTop flex-column border-bottom-f7f7f7">
				<view class="flex-column  ">
					<view class="padding_10rpx_0">
						实付金额
					</view>
					<view class="padding_10rpx_0 font-weight_bold" style="color: rgb(255, 0, 0);font-size: 60rpx;">
						￥{{deductionType.amount?deductionType.amount:deductionType.changeValue}}
					</view>


				</view>

			</view>
			<view class="paymentMethod" v-if="userInfo">
				<view class="flex-start-center">
					<view class="line">

					</view>
					<view class="margin-left_16rpx font-weight_bold">
						请选择支付方式
					</view>
				</view>
				<view class="margin-left_30rpx margin-top_10rpx" style="color: rgb(42, 137, 255);">
					<text>余额:{{userInfo.balance}} | 积分：{{userInfo.surplus_integral}} </text>
				</view>
				<view class="margin_20rpx_0 font-weight_bold ">
					线下扫码
				</view>
				<view v-for="(item, index) in items" :key="item.value">
					<!-- <view v-if="index==2" class="margin_20rpx_0 font-weight_bold ">
						线下扫码
					</view> -->
					<view class="cashierSelection">
						<view class=" flex-between ">
							<view class="flex">
								<image class="image " :src="item.img" mode=""></image>
								<view class=" margin-left_20rpx">
									{{item.name}}
								</view>
							</view>

							<label class="radio">
								<radio-group @change="e=>radioChange(e,index)">
									<label class="uni-list-cell uni-list-cell-pd">
										<view>
											<radio style="transform:scale(0.7)" :value="item.value"
												:checked="index == current" />
										</view>

									</label>
								</radio-group>
							</label>
						</view>
					</view>
				</view>

			</view>
		</view>


		<view class="nextBtn flex" @click="nextPay()">
			支付
		</view>

		<!-- 领取优惠券 -->
		<sunui-popup ref="receiveCouponPopup">
			<template v-slot:content>

				<view class="receiveCouponContain flex-column-Jstart">

					<view class="top flex-between">
						<view class="">

						</view>
						<text>选择我的优惠券</text>
						<uni-icons @click='closeWriteOffIcon()' class="uniIcon" type="clear" size="30"
							style="color: #07070791;">
						</uni-icons>
					</view>
					<mescroll-body ref="mescrollRef" :height="windowHeight+'rpx'" @init="mescrollInit"
						@down="downCallback" @up="upCallback" :up="upOption" :down="downOption">
						<block v-for="(item,index) in list" :key="index">
							<view class="content ">
								<view class="positionCoupon  flex">
									<text class="font-overflow">{{item.name}}</text>
								</view>
								<view class="couponPrice">
									<view class="flex-between ">
										<view class="flex">
											<view class="left">
												<text style="color: rgb(255, 0, 0)">￥</text>
												<text
													style="color: rgb(255, 0, 0);font-family: Inter;font-size: 64rpx;">{{totelName(item.discount_intensity)}}</text>
											</view>
											<view class="flex-columns"
												style="height: 77rpx;justify-content: space-between;">
												<text
													style="color: rgb(255, 0, 0);font-size: 28rpx">{{ item.type === 3 ? '无门槛福利优惠券' : '满' + totelName(item.trigger_amount) + '减' +totelName(item.discount_intensity)  + '元' }}</text>
												<text
													style="color:rgb(153, 153, 153);font-size: 24rpx">{{extractedDate(item.effective_time) }}到期
												</text>
											</view>
										</view>
										<view class="claimNow flex" @click="receiveCoupons(item,index)">
											{{selectCouponIndex==index?'取消选择':'立即选择'}}
										</view>
									</view>
								</view>
							</view>
						</block>
					</mescroll-body>


				</view>

			</template>
		</sunui-popup>
	</view>
</template>

<script>
	export default {
		components: {

		},
		data() {
			return {
				tabIndex: 4,
				current: 0,

				items: [
					// {


					// 		value: '6',
					// 		name: '微信支付',
					// 		checked: 'true',
					// 		img: '../../../static/会员卡管理端/组合 920.png'
					// 	},
					// 	{


					// 		value: '7',
					// 		name: '支付宝支付',

					// 		img: '../../../static/会员卡管理端/组合 917.png'
					// 	},
					{


						value: '2',
						name: '微信充值',

						img: '../../../static/会员卡管理端/组合 920.png'
					},
					{


						value: '3',
						name: '支付宝支付',

						img: '../../../static/会员卡管理端/组合 917.png'
					}, {


						value: '4',
						name: '现金充值',

						img: '../../../static/会员卡管理端/组合 918.png'
					},
					{


						value: '5',
						name: 'pos充值',
						checked: 'true',
						img: '../../../static/会员卡管理端/组合 919.png'
					}


				],
				vModelValue: 1,
				deductionType: null,
				discountPrice: '',
				discount: '',
				downOption: {
					auto: true
				},
				range: [{
						"value": 0,

					},


				],
				range1: [{
						"value": 1,

					},


				],
				// 选择优惠券索引
				selectCouponIndex: 100,
				// 上拉配置项
				upOption: {
					auto: true
				},
				token: uni.getStorageSync('login').token,
				windowHeight: '',
				list: [],
				form: {
					id: '',

					amount: '',
					type: 2
				},
				productInformation: null,
				deduction_integral_ratio: null,
				isPay: false,
				userInfo: null,
				isCustom:false
			}
		},

		onLoad(options) {
			uni.getSystemInfo({
				success: (res) => {
					this.windowHeight = res.windowHeight * 2 - 800;
				},

			});
			console.log(options)
			// 0 消费扣款 1 余额充值 2开通套餐卡

			this.form.id = options.id
			this.form.amount = options.amount ? options.amount : options.changeValue
			if(options.changeValue){
				
				console.log('进来了')
				this.isCustom=true
				
			}
			// this.$sun.assignObject(this.form, {
			// 	...options
			// })

			this.deductionType = options
			console.log(this.deductionType, 'this.deductionType')
			this.getUserInfo(this.form.id)

		},
		onShow() {
			this.mescroll?.resetUpScroll();
			this.$at.releaseKey('submitPay');
			if (uni.getStorageSync('shoplDetails')) {
				console.log(uni.getStorageSync('shoplDetails'))
				this.productInformation = uni.getStorageSync('shoplDetails')
				this.init()
			}
		},
		computed: {
			finalPrice: function() {
				return function(price, couponPrice) {
					let result
					console.log(price, couponPrice)
					result = (price * this.discount) / 100
					if (this.productInformation.buying_pattern == 1) {
						result = (result - couponPrice) - this.deduction_integral_ratio;
						console.log(result)
					} else {
						result = result - couponPrice;
					}
					// result = result - couponPrice;
					this.form.amount = Math.max(0, result.toFixed(2))

					return Math.max(0, result.toFixed(2));
				};


			},
			extractedDate: function() {
				return function(time) {

					return time.split(' ')[0];
				};
			},
			totelName: function() {
				return function(nums) {
					let num
					if (nums.endsWith(".00")) {
						num = nums.slice(0, -3); // 去除末尾的 ".00"
					}
					if (nums >= 10000) {
						let remainder = num % 10000;
						let quotient = Math.floor(num / 10000);
						let decimal = Math.floor(remainder / 1000);
						return quotient + '.' + decimal + '万';
					} else {
						console.log(nums)
						return num?num:nums;
					}
				};
			},
		},
		methods: {
			async getUserInfo(userId) {


				const ress = await this.$http.post({
					url: this.$api.userinfo,
					data: {

						uid: userId

					},
					headers: {
						'Authorization': `Bearer ${this.token}`
					}

				})
				console.log(ress)
				if (ress.code == 0) {

					this.userInfo = ress.data

					// 跳转到登录页面

					// this.$sun.toast(ress.msg, 'none')




				} else {

					this.$sun.toast(ress.msg, 'none')
				}

			},
			nextPay() {
				console.log({

					type: this.form.type,
					id: this.userInfo.id,
					amount: this.form.amount,
					auth_code: this.userInfo.random_code
				})
				this.$at.uniDoFunc({
					key: 'submitPay',
					success: async () => {
						this.$at.lockKey('submitPay');
						// 登录 需要进行判断当前账号密码 和账号归属店铺及角色是否又选择
						console.log(this.form)
						this.$at.releaseKey('submitPay');
						const result = await this.$http.post({
							url: this.$api.rechargeOrder,
							data: {

								type:this.form.type,
								id:this.userInfo.id,
								amount:this.form.amount,
								auth_code:this.userInfo.random_code
							},
							headers: {
								'Authorization': `Bearer ${this.token}`
							}

						})
						if (result.code == 0) {
							this.$sun.toast(result.msg, 'none')
							this.$at.releaseKey('submitPay');
							setTimeout(()=>{
								this.$sun.navBack()
							},1000)
						} else {
							this.$sun.toast(result.msg, 'none')
							this.$at.releaseKey('submitPay');

						}



					}
				});
			},
			async init() {

				const result = await this.$http.post({
					url: this.$api.gooodsDiscount,
					data: {
						goods_id: this.productInformation.id,
						uid: this.form.id

					},
					headers: {
						'Authorization': `Bearer ${this.token}`
					}

				})
				if (result.code == 0) {

					this.discount = result.data.discount
				} else {
					this.$sun.toast(result.msg, 'none')
				}
			},
			receiveCoupons(item, index) {
				if (this.selectCouponIndex == index) {
					console.log('取消选择', this.selectCouponIndex, index)
					this.selectCouponIndex = 100
					this.discountPrice = ''
					this.form.coupon_id = ''
				} else {
					if (item.type !== 3 && this.currentBalance < item.trigger_amount) {
						this.$sun.toast('优惠券不满足当前状态', 'none')
						return
					} else {
						this.selectCouponIndex = index

						this.form.coupon_id = item.id
						console.log(item)
						// 这里需要判断当前的余额是否大于优惠卷 如果优惠券大于余额不可以折扣（前提是满减券和新人券）


						this.discountPrice = item.discount_intensity
					}

				}
				this.$refs.receiveCouponPopup.close()

			},
			selsectProduct() {
				this.$sun.navGo('/pages/cashierSystem/detailsProduct/detailsProduct')
			},
			// 改变数字
			changeNumber(num) {
				console.log(num)
				this.form.number = num
			},
			async radioChange(e, index) {
				console.log(e)
				this.form.type = e.detail.value
				this.current = index




			},
			// 领取优惠券
			receiveCoupon() {


				this.$refs.receiveCouponPopup.show({
					anim: 'bottom',
					position: 'bottom',
					shadeClose: false, //false使用户不能点击其它关闭页面
					topclose: false,
					zIndex: 99999
				});

			},
			async upCallback(scroll) {

				const result = await this.$http.post({
					url: this.$api.userCouponList,
					data: {
						page: scroll.num,
						limit: 10,
						uid: this.form.id

					},
					headers: {
						'Authorization': `Bearer ${this.token}`
					}

				})
				if (result.code == 0) {

					console.log('地址管理列表', this.productInformation);
					// 判断当前 商品分类id 和我们的优惠券id是否相等（包括分类id为0） 
					this.mescroll.endByPage(result.data.list.length, this.$sun.pagingSum(result.data.count, 10));
					if (scroll.num == 1) this.list = [];
					this.list = this.list.concat(result.data.list);
					this.list = this.list.filter((item) => {
						return item.classify_id == this.productInformation.classify_id || item.classify_id ==
							0;
					})
					console.log('this.list', this.list, this.list.length);
				}
			},
		}
	}
</script>

<style lang="less" scoped>
	.receiveCouponContain {
		background-color: #fff;
		height: 50vh;



		.top {
			padding: 30rpx 0;
			width: 100%;

			text {
				color: rgb(0, 0, 0);
				font-size: 36rpx;
				font-weight: 400;
			}
		}

		.content {

			width: 698rpx;
			height: auto;
			overflow-x: auto;
			border-radius: 20rpx;
			margin-bottom: 20rpx;
			background: rgb(255, 242, 242);

			.positionCoupon {
				padding: 8rpx;
				width: 154rpx;
				height: 50rpx;
				border-radius: 20rpx 0rpx 20rpx 0rpx;
				color: rgb(255, 0, 0);
				background: rgb(255, 219, 219);
				font-size: 24rpx;
			}

			.couponPrice {
				padding: 20rpx 26rpx;

				.left {
					margin-right: 32rpx;
				}

				.claimNow {
					width: 144rpx;
					height: 58rpx;
					border-radius: 25rpx;
					color: #fff;
					background: rgb(255, 0, 0);
				}
			}
		}

		.bottom {

			border-radius: 600rpx;
			width: 662rpx;
			height: 96rpx;
			box-shadow: 0px 4px 4px 0px rgba(28, 197, 45, 0.2);
			background: rgb(255, 0, 0);
			color: #fff;
			position: fixed;
			bottom: 20rpx;
		}
	}






	.nextBtn {
		position: fixed;
		bottom: 20rpx;
		width: 90%;
		height: 96rpx;
		background: rgb(0, 87, 254);
		color: rgb(255, 255, 255);
		margin-left: 40rpx;
	}

	.cashierDeductionPage {
		.viewDetailsTop {
			width: 750rpx;
			padding: 40rpx 0;
			background: rgb(255, 255, 255);

			.avatar {
				width: 116rpx;
				height: 116rpx;
			}

			.orderPageDetail {
				margin-top: 20rpx;
				padding: 40rpx;
				width: 100%;
				background: rgb(255, 255, 255);

				.orderPageDescribe {
					// padding-right: 90rpx;

					.img {
						width: 230.02rpx;
						height: 232rpx;
					}

				}

				.Deduction {
					margin-top: 46rpx;
				}
			}

		}

		.paymentMethod {
			.line {
				width: 6px;
				height: 16px;
				background: rgb(42, 137, 255);
			}

			margin-top: 30rpx;
			padding: 40rpx;
			background: rgb(255, 255, 255);
		}

		.cashierSelection {

			padding: 30rpx;

			.image {
				width: 56rpx;
				height: 56rpx;
			}

			background: rgb(255, 255, 255);
		}

		.cashierSelectionContent {
			margin-top: 10rpx;
			padding: 30rpx;
			width: 332.96rpx;
			height: 171.56rpx;

			background: rgb(255, 246, 246);
		}

		.cashierSelectionContent-noActive {
			margin-top: 10rpx;
			padding: 30rpx;
			width: 332.96rpx;
			height: 171.56rpx;

			box-sizing: border-box;
			border: 2rpx solid rgb(228, 227, 227);
			background: rgb(255, 255, 255);
		}

		.viewDetails {
			background: rgb(255, 255, 255);
		}
	}

	page {
		background: #f6f6f6;
	}
</style>